package com.cstolua.lib;

import java.io.File;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.cstolua.game.MainGameActivity;
import com.unity3d.player.UnityPlayer;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.JsonReader;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;

public class Unity3dHelper {
	private static String sPackageName;
	private static String sAssetsPath;
	private static Activity sActivity = null;
	private static AssetManager sAssetManager;

	public static void init(final Activity activity) {
		sActivity = activity;
		final ApplicationInfo applicationInfo = activity.getApplicationInfo();
		sPackageName = applicationInfo.packageName;
		sAssetManager = activity.getAssets();
		Log.d(MainGameActivity.TAG, "Unity3dHelper.init");

	}

	public static void onNativeInit() {
		Log.d(MainGameActivity.TAG, "Unity3dHelper.onNativeInit");
		nativeSetApkPath(getAssetsPath());
		nativeSetContext((Context) sActivity, sAssetManager);
	}

	public static String getCocos2dxPackageName() {
		return sPackageName;
	}

	public static String getAssetsPath() {
		if (sAssetsPath == "") {
			int versionCode = 1;
			try {
				versionCode = sActivity.getPackageManager().getPackageInfo(sPackageName, 0).versionCode;
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}
			String pathToOBB = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/obb/"
					+ sPackageName + "/main." + versionCode + "." + sPackageName + ".obb";
			File obbFile = new File(pathToOBB);
			if (obbFile.exists())
				sAssetsPath = pathToOBB;
			else
				sAssetsPath = sActivity.getApplicationInfo().sourceDir;
		}

		return sAssetsPath;
	}

	public static int showAlert(String json_str) {
		Log.d(MainGameActivity.TAG, json_str);

		try {
			final JSONObject JSON = new JSONObject(json_str);
			final String title = JSON.getString("title");
			final String message = JSON.getString("message");
			JSONArray jarry = JSON.getJSONArray("buttonLabels");
			final String[] buttonLabels = new String[jarry.length()];

			for (int i = 0; i < jarry.length(); i++) {
				buttonLabels[i] = jarry.getString(i);
			}
			UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
				@Override
				public void run() {

					AlertDialog.Builder dialogPopupBuilder = new AlertDialog.Builder(
							new ContextThemeWrapper(UnityPlayer.currentActivity, GetTheme()));
					dialogPopupBuilder.setTitle(title);
					dialogPopupBuilder.setMessage(message);
					dialogPopupBuilder.setPositiveButton(buttonLabels[0], new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							UnityPlayer.UnitySendMessage("GameManager", "OnDialogPopUpCallBack", "1");
						}
					});
					for (int i = 1; i < buttonLabels.length; i++) {
						final String index = (i+1) + "";
						dialogPopupBuilder.setNegativeButton(buttonLabels[i], new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								UnityPlayer.UnitySendMessage("GameManager", "OnDialogPopUpCallBack", index);
							}
						});
					}
					dialogPopupBuilder.setCancelable(false);
					dialogPopupBuilder.show();
				}
			});
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return 0;
	}

	@SuppressLint("InlinedApi")
	private static int GetTheme() {
		int theme = 0;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			theme = android.R.style.Theme_Material_Light_Dialog;
		} else {
			theme = android.R.style.Theme_Holo_Dialog;
		}
		return theme;
	}

	public static void OpenAppRatingPage(String url) {
		Uri uri = Uri.parse(url);
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		UnityPlayer.currentActivity.startActivity(intent);
	}

	private static native void nativeSetApkPath(final String pApkPath);

	private static native void nativeSetContext(final Context pContext, final AssetManager pAssetManager);
}
